<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>用户管理</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<jsp:include page="${pageContext.request.contextPath }/resource_path.jsp" flush="true"/>
	<link rel="stylesheet" media="all" href="${pageContext.request.contextPath }/assets/formSelects/formSelects-v4.css">
</head>
<body class="layui-anim layui-anim-up">
<div class="x-nav">
	<span class="layui-breadcrumb">
 			<a href="">首页</a>
		<a>
			<cite>用户管理</cite>
		</a>
	</span>
   </div>
<div class="x-body">
	<div class="layui-row">
		<div class="layui-form layui-col-md12 x-so">
			<input type="text" name="keyword" id="keyword"  placeholder="请输入用户名" autocomplete="off" class="layui-input">
			<button class="layui-btn layui-btn-normal" data-type="reload"><i class="layui-icon layui-icon-search"></i>检索</button>
		</div>
	</div>
	<script type="text/html" id="toolbarDemo">
		<div class="layui-btn-container">
			<button class="layui-btn layui-btn-warm" lay-event="add"><i class="layui-icon layui-icon-add-circle-fine"></i>新增</button>
			<button class="layui-btn layui-btn-danger" lay-event="delete"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
		</div>
	</script>
	<table class="layui-hide" id="test" lay-filter="test"></table>
	<script type="text/html" id="barDemo">
		<a class="layui-btn layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit">编辑</i></a>
		<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del"><i class="layui-icon layui-icon-delete">删除</i></a>
	</script>
</div>

<!-- 弹框 -->
<div id="formDiv" hidden>
	<div class="box">
		<form class="layui-form layui-card-body" id="addform">
			<input hidden id="id" name="id">
			<div class="layui-form-item">
				<div class="layui-inline">
					<label class="layui-form-label">姓名</label>
					<div class="layui-input-inline">
						<input lay-verify="userName" class="layui-input" type="text" id="userName" name="userName" style="width: 375px">
						<span class="xing" style="margin-left: 390px;font-size: 24px;"></span>
					</div>
				</div>
				<!-- <div class="layui-inline" style="float: right;margin-right: 3em;margin-top: 10px;">
					<font style="color:red; font-size: 24px;">*</font>
				</div> -->
			</div>
			<div class="layui-form-item">
				<div class="layui-inline">
					<label class="layui-form-label">用户名</label>
					<div class="layui-input-inline">
						<input lay-verify="accountName" class="layui-input" type="text" id="accountName" name="accountName" style="width: 375px">
						<span class="xing" style="margin-left: 390px;font-size: 24px;"></span>
					</div>
				</div>
				<!-- <div class="layui-inline" style="float: right;margin-right: 3em;margin-top: 10px;">
					<font style="color:red; font-size: 24px;">*</font>
				</div> -->
			</div>
			<div class="layui-form-item">
				<div class="layui-inline">
					<label class="layui-form-label">工号</label>
					<div class="layui-input-inline">
						<input lay-verify="jobNumber" class="layui-input" type="text" id="jobNumber" name="jobNumber" style="width: 375px">
						<span class="xing" style="margin-left: 390px;font-size: 24px;"></span>
					</div>
				</div>
				<!-- <div class="layui-inline" style="float: right;margin-right: 3em;margin-top: 10px;">
					<font style="color:red; font-size: 24px;">*</font>
				</div> -->
			</div>
			<!-- <div class="layui-form-item">
				<div class="layui-inline">
					<label class="layui-form-label">密码</label>
					<div class="layui-input-inline">
						<input lay-verify="password" class="layui-input" type="password" id="password" name="password" style="width: 375px">
					</div>
				</div>
				<div class="layui-inline" style="float: right;margin-right: 3em;margin-top: 10px;">
					<font style="color:red; font-size: 24px;">*</font>
				</div>
			</div> -->
			<div class="layui-form-item">
				<div class="layui-inline">
					<label class="layui-form-label">性别</label>
					<div class="layui-input-inline" style="width: 375px">
						<select lay-verify="sex" id="sex" name="sex">
							<option value="0">男</option>
							<option value="1">女</option>
						</select>
						<span class="xing" style="margin-left: 390px;font-size: 24px;"></span>
					</div>
				</div>
				<!-- <div class="layui-inline" style="float: right;margin-right: 3em;margin-top: 10px;">
					<font style="color:red; font-size: 24px;">*</font>
				</div> -->
			</div>
			<div class="layui-form-item">
				<div class="layui-inline">
					<label class="layui-form-label">角色</label>
					<div class="layui-input-inline" style="width: 375px">
						<input class="layui-hide" id="roleId" name="roleId" lay-verify="roleId" lay-filter="roleId" readonly="readonly">
						<input class="layui-input" id="roleName" lay-verify="roleName" lay-filter="roleName" name="roleName" readonly="readonly" onfocus="roleDiv()">
						<div id="div1" hidden>
							<c:forEach items="${rList }" var="role">
								<input type="checkbox" name="roleList" lay-filter="roleList" value="${role.id}" title="${role.roleName}">
							</c:forEach>
						</div>
						<span class="xing" style="margin-left: 390px;font-size: 24px;"></span>
					</div>
				</div>
				<!-- <div class="layui-inline" style="float: right;margin-right: 3em;margin-top: 10px;">
					<font style="color:red; font-size: 24px;">*</font>
				</div> -->
			</div>
<%-- 			<div class="layui-form-item">
				<div class="layui-inline">
					<label class="layui-form-label">角色</label>
					<div class="layui-input-inline" style="width: 375px">
						<select lay-verify="roleId" id="roleId" name="roleId" xm-select="select1">
							<option value="">--请选择角色--</option>
							<c:forEach items="${rList }" var="role">
								<option value="${role.id }">${role.roleName }</option>
							</c:forEach>
						</select>
					</div>
				</div>
				<div class="layui-inline" style="float: right;margin-right: 3em;margin-top: 10px;">
					<font style="color:red; font-size: 24px;">*</font>
				</div>
			</div> --%>
			<div class="layui-form-item">
				<div class="layui-inline">
					<label class="layui-form-label">客户（选填）</label>
					<div class="layui-input-inline" style="width: 375px">
						<select lay-verify="customer_id" id="customer_id" name="customer_id" lay-filter="customer_id">
							<option value="">--请选择客户--</option>
							<c:forEach items="${customerList }" var="customer">
								<option value="${customer.id }">${customer.customer_name }</option>
							</c:forEach>
						</select>
					</div>
				</div>
			</div>
			<div class="layui-form-item">
				<div class="layui-inline">
					<label class="layui-form-label">部门</label>
					<div class="layui-input-inline" style="width: 375px">
						<select lay-verify="deptId" id="deptId" name="deptId" lay-filter="deptId">
							<option value="">--请选择部门--</option>
							<c:forEach items="${deptList }" var="dept">
								<option value="${dept.id }">${dept.dept_name }</option>
							</c:forEach>
						</select>
					</div>
				</div>
			</div>
			<div class="layui-form-item">
				<div class="layui-inline">
					<label class="layui-form-label">岗位</label>
					<div class="layui-input-inline" style="width: 375px">
						<select lay-verify="postId" id="postId" name="postId" lay-filter="postId">
							<option value="">--请选择岗位--</option>
							<c:forEach items="${postList }" var="post">
								<option value="${post.id }">${post.post_name }</option>
							</c:forEach>
						</select>
					</div>
				</div>
			</div>
			<div class="layui-form-item">
				<div class="layui-inline">
					<label class="layui-form-label">电话</label>
					<div class="layui-input-inline">
						<input lay-verify="phone" class="layui-input" type="text" id="phone" name="phone" style="width: 375px">
						<span class="xing" style="margin-left: 390px;font-size: 24px;"></span>
					</div>
				</div>
				<!-- <div class="layui-inline" style="float: right;margin-right: 3em;margin-top: 10px;">
					<font style="color:red; font-size: 24px;">*</font>
				</div> -->
			</div>
			<div class="layui-form-item">
				<div class="layui-input-block">
					<button class="layui-btn layui-btn-primary" lay-submit lay-filter="addform" id="subform">提交</button>
					<button class="layui-btn layui-btn-primary" style="margin-left:240px">取消</button>
				</div>
			</div>
		</form>
	</div>
</div>

<script>
function roleDiv(){
	$("#div1").removeAttr("hidden");
}
//全局定义一次, 加载formSelects
layui.config({
    base: '${pageContext.request.contextPath }/assets/formSelects/' //此处路径请自行处理, 可以使用绝对路径
}).extend({
    formSelects: 'formSelects-v4'
});
layui.use(['table','layer','upload','form','formSelects'], function(){
	var table = layui.table;
	var layer = layui.layer,
    form = layui.form,
    formSelects=layui.formSelects;
	//联动
	form.on('select(deptId)', function(data){
		$("#postId").empty();
		form.render();
		if(data.value == "" || data.value == undefined || data.value == null){
		}else{
			//通过部门id查询岗位列表
			var strWhere = 'p.dept_id = '+ data.value + 'and'
			$.ajax({
				type:'post'
				,url:'${pageContext.request.contextPath }/system/selectAllPostList.do'
				,data:{'strWhere':strWhere}
				,dataType:'json'
				,success:function(res){
					$("#postId").find("option").not(":first").remove();
					for(var i = 0;i < res.length;i++){
						$("#postId").append('<option value="'+res[i].id+'">'+res[i].post_name+'</option>');
					}
					form.render();
				}
			})
		}
	}); 
	var $ = layui.jquery, active = {
			reload:function () {
				var keyword = $("#keyword").val();
				var strWhere = "[user].status = 0 and [user].isdel = 0 and [user].accountName like '%"+keyword+"%' and ";
				table.reload('contenttable',{
					method:'get',
					where:{"strWhere": strWhere}
					,page: {
	                    curr: 1//重新从第 1 页开始
	                }
				});
			}
		}
	$('.layui-btn').on('click', function(){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
	table.render({
	    elem: '#test'
	    ,url:'${pageContext.request.contextPath }/system/selectSysUserList.do'
	    ,title: '用户数据表'
	    ,toolbar: '#toolbarDemo'
	    ,id :'contenttable'
	    ,limits:[10,20,30]
	    ,cols: [[
			{type: 'checkbox', fixed: 'left'}
	      	,{field:'', title:'序号', sort: true, type:'numbers', width: 60}
	      	,{field:'userName', title:'姓名'}
	      	,{field:'accountName', title:'用户名'}
	      	,{field:'jobNumber', title:'工号'}
	      	,{field:'roleName', title:'角色'}
	      	,{field:'customer', title:'客户', templet: function(res){
	      		if(res.customer!=null){
		    		return res.customer.customer_name;
	      		}else{
	      			return "";
	      		}
		     }}
	      	,{field:'dept', title:'部门', templet: function(res){
	      		if(res.dept!=null){
		    		return res.dept.dept_name;
	      		}else{
	      			return "";
	      		}
		     }}
	      	,{field:'post', title:'岗位', templet: function(res){
	      		if(res.post!=null){
		    		return res.post.post_name;
	      		}else{
	      			return "";
	      		}
		      }}
	      	,{field:'sex', title:'性别', templet: function(res){
	    	  if (res.sex == 0) {
	    		  return '男';
			} else {
				return '女';
			}
	      }}
	      ,{field:'phone', title:'电话'}
	      ,{fixed: 'right', title:'操作', toolbar: '#barDemo',width:158}
	    ]]
	    ,page: true
	    ,done:function(){
	    	$('th').css({
                'background-color': '#009688', 'color': '#fff','font-weight':'bold',
            })
	    }
	});
	//监听复选框事件
	table.on('checkbox(test)',function(obj){
		if(obj.checked == true && obj.type == 'all'){ 
			//点击全选 
			$('.layui-table-body table.layui-table tbody tr').addClass('layui-table-click'); 
		}else if(obj.checked == false && obj.type == 'all'){ 
			//点击全不选 
			$('.layui-table-body table.layui-table tbody tr').removeClass('layui-table-click'); 
		}else if(obj.checked == true && obj.type == 'one'){ 
			//点击单行
			if(obj.checked == true){ 
				obj.tr.addClass('layui-table-click'); 
			}else{ 
				obj.tr.removeClass('layui-table-click'); 
			} 
		}else if(obj.checked == false && obj.type == 'one'){ 
			//点击全选之后点击单行 
			if(obj.tr.hasClass('layui-table-click')){
				obj.tr.removeClass('layui-table-click'); 
			} 
		}
	})
	//头事件
	table.on('toolbar(test)', function(obj){
		var checkStatus = table.checkStatus(obj.config.id);
		switch(obj.event){
    		case 'add':
    		layer.open({
    			  type: 1 		//Page层类型
    			  ,area: ['590px', ''] //宽  高
    			  ,skin: 'alert-skin'
    			  ,title: '新增用户'
    			  ,shade: 0.6 	//遮罩透明度
    			  ,shadeClose: true //点击遮罩关闭
    			  ,maxmin: true //允许全屏最小化
    			  ,anim: 1 		//0-6的动画形式，-1不开启
    			  ,content: $('#formDiv')
    			  ,success: function () {
    				  document.getElementById("addform").reset();
    				  $("#accountName").removeAttr("readonly")
    				  $("#jobNumber").removeAttr("readonly")
    				  $("#accountName").css("background","#FFF");
    				  $("#jobNumber").css("background","#FFF");
    				 //清空岗位信息
    				  $("#postId").empty();
    				  form.render();
    				  
    			  }
    			  ,end: function () {
    				  var formDiv = document.getElementById('formDiv');
    				  formDiv.style.display = '';
    			  }
    		});
    		break;
    		//批量删除
    		case 'delete':
    			var data = checkStatus.data;
	        	if(data.length==0){
	        		toastr.warning("请至少选择一条记录！");
	        	}
	        	var idArr = new Array();
	        	for(var i=0;i<data.length;i++){
	        		idArr[i] = data[i].id;
	        		layer.confirm('确定删除吗？', function(index){
	        			$.ajax({
	        		    	type:'post',
	        		    	url:'${pageContext.request.contextPath }/system/deleteUserById.do',
	        		    	data:{"idArr":idArr},
	        		    	success:function(data){
	        		    		if(data>0){
	        		    			toastr.success("删除成功！");
	        		    			/* setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
	        							//关闭模态框
	        							// 父页面刷新
	        							window.location.reload();
	        						},2000); */
	                                table.reload('contenttable',{
	                                    method:'get',
	                	                page: {
	                	                    curr: 1//重新从第 1 页开始
	                	                }
	                                });
	        		    		}else{
	        		    			toastr.warning("删除失败！");
	        		    		}
	        		    	}

	        		    })
	        		    layer.close(index);
	        		})
	        	}
    		break;
		}
	});

	//监听行工具事件
	table.on('tool(test)', function(obj){
		var data = obj.data;
		if(obj.event === 'del'){
		  layer.confirm('确定删除吗？', function(index){
		    var id = obj.data.id;
		    var idArr = new Array();
		    idArr[0] = id;
		    $.ajax({
		    	type:'post',
		    	url:'${pageContext.request.contextPath }/system/deleteUserById.do',
		    	data:{"idArr":idArr},
		    	success:function(data){
		    		if(data>0){
		    			toastr.success("删除成功！");
		    			/* setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
							//关闭模态框
							// 父页面刷新
							window.location.reload();
						},2000); */
                        table.reload('contenttable',{
                            method:'get',
        	                page: {
        	                    curr: 1//重新从第 1 页开始
        	                }
                        });
		    		}else{
		    			toastr.warning("删除失败！");
		    		}
		    	}

		    })
		    layer.close(index);
		  });
		} else if(obj.event === 'edit'){
			layer.open({
			  type: 1 		//Page层类型
			  ,area: ['590px', ''] //宽  高
			  ,skin: 'alert-skin'
			  ,title: '修改用户'
			  ,shade: 0.6 	//遮罩透明度
			  ,shadeClose: true //点击遮罩关闭
			  ,maxmin: true //允许全屏最小化
			  ,anim: 1 		//0-6的动画形式，-1不开启
			  ,content: $('#formDiv')
			  ,success: function () {
				  //$("#accountName").attr("readonly","readonly");
				  //$("#jobNumber").attr("readonly","readonly");
				  //$("#accountName").css("background","#DDD");
				  //$("#jobNumber").css("background","#DDD");
					//回显表单数据
					for(var i=0;i<Object.entries(data).length;i++) {
						var id = '#' + Object.entries(data)[i][0];
						var text = Object.entries(data)[i][1];
						$(id).val(text);
					}
					$("#roleName").val(data.roleName)
					//清空岗位信息
   				  	$("#postId").empty();
   				  	form.render();
   				  	if(data.deptId == "" || data.deptId == undefined || data.deptId == null){
   				  	}else{
						//通过部门id查询岗位列表
						var strWhere = 'p.dept_id = '+ data.deptId + 'and'
						$.ajax({
							type:'post'
							,url:'${pageContext.request.contextPath }/system/selectAllPostList.do'
							,data:{'strWhere':strWhere}
							,dataType:'json'
							,success:function(res){
								$("#postId").find("option").not(":first").remove();
								for(var i = 0;i < res.length;i++){
									$("#postId").append('<option value="'+res[i].id+'">'+res[i].post_name+'</option>');
								}
								form.render();
								$("#postId").val(data.postId);
								form.render();
							}
						})
   				  	}
					var length = $("#div1 input").length;
					for(var i = 0;i<length;i++){
						var inputValue = $("#div1 input")[i].value;
						var roleIdList = data.roleId;
						var roleIds = roleIdList.split(",");
						for(var x = 0; x<roleIds.length;x++){
							if(inputValue == roleIds[x]){
								$("#div1 input")[i].checked = "true";
								form.render();
							}
						}
					}
				  }	
				  ,end: function () {
					  	var length = $("#div1 input").length;
					  	for(var i = 0;i<length;i++){
					  		$("#div1 input")[i].checked = "";
						  	form.render();
						}
					  	var formDiv = document.getElementById('formDiv');
					  	formDiv.style.display = '';
			  	  }
			});
		}
	});
	/**
	*	复选框事件
	*/
	form.on('checkbox(roleList)', function(obj){
	    var value = obj.value+",";
	    var title = obj.elem.title+",";
		var ischecked = obj.elem.checked;
		if(ischecked){
		    $("#roleId").val($("#roleId").val()+value);
		    $("#roleName").val($("#roleName").val()+title);
		}else{
			var attrId = $("#roleId").val();
			var attrName = $("#roleName").val();
			var attrIds = attrId.split(",");
			var attrNames = attrName.split(",");
			var values = value.split(",");
			var title = title.split(",");
			var newValue = "";
			var newTitle = "";
			for(var i=0;i<attrIds.length;i++){
				if(values[0] != attrIds[i] && attrIds[i] != ""){
					newValue = newValue+attrIds[i]+",";
					newTitle = newTitle+attrNames[i]+",";
				}
			}
			$("#roleId").val(newValue);
			$("#roleName").val(newTitle);
		}
	}); 
	/**
     * 表单校验
     */
    form.verify({
    	//value：表单的值、item：表单的DOM对象
    	userName: function(value, item){
    		if(value == ''){
    			return '姓名不能为空';
    		}
    	},
    	accountName: function(value, item){
    		if(value == ''){
    			return '用户名不能为空';
    		}else{
                var flg = false;
                $.ajax({
                    type:'post',
                    data:'accountName='+value+'&status=0'+'&isdel=0',
                    url:'${pageContext.request.contextPath}/system/selectSysUserByMution.do',
                    dataType: 'JSON',
                    async: false,
                    success:function (data) {
                        if(data.length == 0){
                            flg  = true;
                        }else if(data.length == 1){
                            var ma = $.trim($("#id").val());
                            if (ma == data[0].id) {
                                flg  = true;
                            }else{
                                flg = false;
                            }
                        }else{
                            flg = false;
                        }

                    }
                });
                if(!flg){
                    return '用户名不能重复';
                }
            }
    	},
		/* password: function(value, item){
    		if(value == ''){
    			return '密码不能为空';
    		}
    	}, */
    	sex: function(value, item){
    		if(value == ''){
    			return '性别不能为空';
    		}
    	},
    	roleName: function(value, item){
    		if(value == ''){
    			return '角色不能为空';
    		}
    	},
    	roleId: function(value, item){
    		if(value == ''){
    			return '角色不能为空';
    		}
    	},
    	phone: function(value, item){
    		if(value == ''){
    			return '电话不能为空';
    		}/* else if(!/^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/.test(value)){
    			return '电话号码不正确';
    		} */
    	},
    	jobNumber: function(value, item){
    		if(value == ''){
    			return '工号不能为空';
    		}else{
                var flg = false;
                $.ajax({
                    type:'post',
                    data:'jobNumber='+value+'&status=0'+'&isdel=0',
                    url:'${pageContext.request.contextPath}/system/selectSysUserByMution.do',
                    dataType: 'JSON',
                    async: false,
                    success:function (data) {
                        if(data.length == 0){
                            flg  = true;
                        }else if(data.length == 1){
                            var ma = $.trim($("#id").val());
                            if (ma == data[0].id) {
                                flg  = true;
                            }else{
                                flg = false;
                            }
                        }else{
                            flg = false;
                        }

                    }
                });
                if(!flg){
                    return '工号不能重复';
                }
            }
    	}
    });
    /**
     * 通用表单提交(AJAX方式)（新增）
     */
    form.on('submit(addform)', function (data) {
    	$("#subform").attr("disabled",true);
    	var accountName= $("#accountName").val();
    	var id= $("#id").val();
    	$.ajax({
    		url : '${pageContext.request.contextPath }/system/countUser.do',
   			data : {"accountName":accountName},
   			type : "post",
   			//dataType : "json",
			}).done(
				function(res) {
					if(res==0 || id != ""){
						$.ajax({
				    		url : '${pageContext.request.contextPath }/system/saveSysUser.do',
				   			data : $('#addform').serialize(),
				   			type : "post",
				   			//dataType : "json",
							}).done(
								function(res) {
									var list = res.split('_');
						  			if (parseInt(list[0]) > 0) {
						  				if(list[1].indexOf('add') != -1){
						  					toastr.success('新增成功！');
						  				}
						  				if(list[1].indexOf('edit') != -1){
						  					toastr.success('修改成功！');
						  				}
						  				/* setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
						  					//关闭模态框
						  					// 父页面刷新
						  					window.location.reload();  
						  				},2000); */
						  				layer.closeAll();
						  				$("#subform").attr("disabled",false);
		                                table.reload('contenttable',{
		                                    method:'get',
		                	                page: {
		                	                    curr: 1//重新从第 1 页开始
		                	                }
		                                });
						  			}else if(parseInt(list[0]) == -2){
						  				toastr.warning('工号已存在！');
						  				$("#subform").attr("disabled",false);
						  			}
								}
							).fail(
								function(res) {
						  			var data = res.responseText;
						  			var list = data.split('_');
									if(list[1].indexOf('add') != -1){
										layer.close(1);
										toastr.error('新增失败！');
										$("#subform").attr("disabled",false);
									}
									if(list[1].indexOf('edit') != -1){
										layer.close(1);
										toastr.error('修改失败！');
										$("#subform").attr("disabled",false);
									}
						  		}
							)
					}else{
						toastr.warning('用户名已存在！');
						$("#subform").attr("disabled",false);
					}
				}
			)
			return false;
    });
});
toastr.options.positionClass = 'toast-top-center'; //提示框的位置设置为中上
</script>

</body>
</html>